package cn.appsys.controller.developer;

import cn.appsys.pojo.*;
import cn.appsys.service.developer.DevUserLoginService;
import cn.appsys.service.developer.DevUserService;
import cn.appsys.tools.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
@Controller
@RequestMapping("/devlist")
public class DevUserController {

    @Resource
    private DevUserService devUserService;
    /**
     * 分页查询
     * @param map
     * @param pageNo
     * @param session
     * @param querySoftwareName
     * @param _queryStatus
     * @param _queryCategoryLevel1
     * @param _queryCategoryLevel2
     * @param _queryCategoryLevel3
     * @param _queryFlatformId
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(ModelMap map, @RequestParam(defaultValue = "1", required = true, value = "pageNo") Integer pageNo
            , HttpSession session,
                       @RequestParam(value="querySoftwareName",required=false) String querySoftwareName,
                       @RequestParam(value="queryStatus",required=false) Integer _queryStatus,
                       @RequestParam(value="queryCategoryLevel1",required=false) Integer _queryCategoryLevel1,
                       @RequestParam(value="queryCategoryLevel2",required=false) Integer _queryCategoryLevel2,
                       @RequestParam(value="queryCategoryLevel3",required=false) Integer _queryCategoryLevel3,
                       @RequestParam(value="queryFlatformId",required=false) Integer _queryFlatformId,
                        @RequestParam(value="devId",required=false) Integer devId
    ){
        //每页显示记录数
        Integer pageSize = 2;
        //分页查询
        PageHelper.startPage(pageNo, pageSize);
        //获取所有用户信息
        List<AppInfo> list=devUserService.getAppInfoListBiz(querySoftwareName,_queryStatus,_queryCategoryLevel1,_queryCategoryLevel2,_queryCategoryLevel3,_queryFlatformId,devId);
        PageInfo<AppInfo> pageInfo = new PageInfo<AppInfo>(list);
        //分页查询所有
        map.addAttribute("page", pageInfo);
        //页面传值所属平台参数flatFormList
        List<DataDictionary>  appFlatform=devUserService.appFlatformBiz();
         map.addAttribute("flatFormList",appFlatform);
         //页面传值app状态码参数statusList
        List<DataDictionary>  devStatus=devUserService.devStatusB();
          map.addAttribute("statusList",devStatus);
        //页面传值一级分类参数categoryLevel1List
        List<AppCategory> appCategories=devUserService.oneSortBiz();
        map.addAttribute("categoryLevel1List",appCategories);
        /**
         * 分页查询
         */
        //软件名称模糊查询
        map.addAttribute("querySoftwareName",querySoftwareName);
        //app状态码查询
        map.addAttribute("queryStatus",_queryStatus);
        //所属平台查询
        map.addAttribute("queryFlatformId",_queryFlatformId);
        //一级分页查询
        map.addAttribute("queryCategoryLevel1",_queryCategoryLevel1);
        //二级分页查询
        map.addAttribute("queryCategoryLevel2",_queryCategoryLevel2);
        //三级查询
        map.addAttribute("queryCategoryLevel3",_queryCategoryLevel3);
        return "developer/appinfolist";
    }

    /**
     * 实现ajax根据pid查询二三级分类
     * @param pid
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/categorylevel",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
    public String categorylevelListAll(Integer pid) {
        AppCategory appCategory = new AppCategory();
        appCategory.setParentId(pid);
        System.out.println("ewqewqe"+appCategory.getParentId() + "\n\n\n");
        //获取二三级分类
        List<AppCategory> appCategories = devUserService.categoryLevel1ListBiz(appCategory);
        //将ArrayList转换成JSON格式
        return JSONArray.toJSONString(appCategories);
    }

    /**
     * 根据id查询
     */
    @RequestMapping(value = "/fomodify")
    public String selectId(Integer id, Model model) {
         AppInfo appInfo=devUserService.fomodifyBiz(id);
         System.out.println("hello>>>>>"+appInfo);
         model.addAttribute("appInfo",appInfo);
        return "developer/appinfoview";
    }

    /**
     * 跳转新增页面
     */
    @RequestMapping("/add")
    public String add(){
        return "developer/appinfoadd";
    }


     /**
     * 查询所属 平台，一级，二级，三级分类
     * @return
     */
//

    /**
     * 跳转到修改页面
     * @return
     */
    /**
     * 根据id查询
     */

     @RequestMapping(value = "/appinfomodifyselectid")
      public  Object  appinfomodify(@RequestParam Integer id, Model model){
         System.err.println("======================");
         AppInfo   appInfo=devUserService.fomodifyBiz(id);
         model.addAttribute("selectList",appInfo);
         //页面传值所属平台参数flatFormList
         List<DataDictionary>  appFlatform=devUserService.appFlatformBiz();
         model.addAttribute("flatFormList",appFlatform);
         //页面传值一级分类参数categoryLevel1List
         List<AppCategory> appCategories=devUserService.oneSortBiz();
         model.addAttribute("categoryLevel1List",appCategories);
         //页面传值二级分类参数categoryLevel1List
         List<AppCategory>categoryLevel2List=devUserService.listaddBiz();
         model.addAttribute("categoryLevel2List",categoryLevel2List);
//         //页面传值二级分类参数categoryLevel1List
//         List<AppCategory>secondary=devUserService.listaddBiz();
//         model.addAttribute("categoryLevel2",categoryLevel2List);
         //页面传值三级分类参数categoryLevel1List
         List<AppCategory>secondary=devUserService.Level3Biz();
         model.addAttribute("categoryLevel3List",secondary);

         return  "developer/appinfomodify" ;
     }
    /**
     * app基础信息修改
     * @param
     * @return
     */
    @RequestMapping(value = "/udatelist",method = RequestMethod.POST)
    public  String update(AppInfo appInfo){
        int count=0;
        count=devUserService.updateBiz(appInfo);
        System.out.println("hello>>>"+count);
        if (count>0){
            return "redirect:/devlist/list";
        }
        return "developer/appinfomodify";
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
     @ResponseBody
    @RequestMapping("/delt")
    public  String del(@RequestParam(value = "id" ,required = false)Integer id){
      int count=devUserService.deleteBiz(id);
      System.out.println("hello"+count);
        return  JSON.toJSONString(count);
    }

    /**
     * 跳转版本添加页面
     * @return
     */
    @RequestMapping(value = "/addversion")
    public  String addVersion(){

    return "developer/appversionadd";
}

    /**
     * 新增版本信息
     * @return
     */
    @RequestMapping(value = "/versionadd")
 public  String versionadd(AppVersion appVersion, @RequestParam(value = "a_downloadLink",required = false)MultipartFile apk,
                           HttpSession session,
                           HttpServletRequest request){
        String idPicPath=null;
        if (!(apk.isEmpty())){
            String  path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
            System.out.println("hello>>>>>>>>"+path);
            System.out.println("hello>>>>>>>>"+idPicPath);
            String  oldFileName=apk.getOriginalFilename();
            System.out.println("hello>>>>>>>>"+oldFileName);

            String prefix=FilenameUtils.getExtension(oldFileName);
            System.out.println("hello>>>>>>>>"+prefix);

            int filesize=500000;
            System.out.println("uploadfiles size=======>"+apk.getSize());
            if (apk.getSize()>filesize){
                request.setAttribute("uploadFileError","*上传大小不得超过500kb");
                return "/devlist/add";
            }else if (prefix.equalsIgnoreCase("apk")){
                String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.apk";
                System.out.println("hello>>>>>>>>>>"+apk.getName());
                File targetFile=new File(path,fileName);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try{
                    apk.transferTo(targetFile);
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("uploadFileError","*上传失败！");
                    return  "/devlist/add";
                }
                idPicPath=path+File.separator+fileName;
            }else {
                request.setAttribute("uploadFileError","*上传格式不正确");
                return  "/devlist/add";
            }
        }
        appVersion.setApkLocPath(idPicPath);
        int count=devUserService.versionaddBiz(appVersion);
        System.out.println("hello>>"+count);
        if (count>0){
            return "redirect:/devlist/list";
        } else{
            return "/devlist/add";
 }
    }
}
